package javaSocket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;


/** 
 * 1- 注意区分  selector.selectedKeys() 和 selector.Keys() 是不一样的
 */
@Slf4j
public class GroupChatServerExample {

    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;


    public static void main(String[] args) throws IOException {
        GroupChatServerExample server = new GroupChatServerExample();
        server.listen();
    }
    public GroupChatServerExample() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            // 将 chanel 注册到 selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  

    public void listen() throws IOException {
        while (true) {
            int count = selector.select(2000);
            if (count > 0) {
                // 有事件待处理
                for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
                    SelectionKey key = it.next();
                    if (key.isAcceptable()) {
                        SocketChannel socketChannel = listenChannel.accept();
                        log.error("客户端连接成功,分配SocketChannel hashCode = {}", socketChannel.hashCode());
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(512));
                        System.out.println(socketChannel.getRemoteAddress() + "上线了");
                    } else if (key.isReadable()) {
                        //  若是可读的
                        readMsg(key);
                    }
                    // 关键一步，别忘了移除此 selectKey 防止重复操作
                    it.remove();
                }
            } else {
                
            }
        }
    }
    
    private void readMsg(SelectionKey key) {
        SocketChannel channel = null;
        try {
             channel = (SocketChannel) key.channel();
            // 获取关联的buffer
            ByteBuffer buffer = (ByteBuffer) key.attachment();
            int count = channel.read(buffer);
            if (count >0){
                String  msg = new String(buffer.array());
                System.out.println("从 客户端读取到内容是："+msg); 
                // 向其他客户端转发消息
                sendMsgToOtherClients(msg,channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
                // 取消注册
                key.channel();
                // 关闭 通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            
        }
    }

    /** 转发消息给其他人
     * @param msg 消息
     * @param self 自己
     */
    private void sendMsgToOtherClients(String msg ,SocketChannel self) throws IOException {
        log.info("服务器转发消息中...");
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel =  key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel !=self){
                SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
                dest.write(buffer);
            }
        }
    }



}
